namespace CRM_Perf_BenchMark
{
    using System;
    using System.Collections.Generic;
    using Microsoft.VisualStudio.TestTools.WebTesting;
    using System.Net;
    using System.Text;
    using System.Xml;
    
    /// <summary>
    /// 1. Starts at Sales homepage
    /// 2. Click on Competitors
    /// 3. Click New
    /// 4. Add relevant data (name)
    /// 5. Click Save and Close
    /// </summary>

    public class CreateNewCompetitor : CrmWebTest
    {
        public void CreateNewCompetitor_PreWebTest(object sender, PreWebTestEventArgs e)
        {
            EntityRequest er = new EntityRequest();
            er.Type = EntityNames.Users;
            er.ReturnAs = EntityNames.Users;
            er.ParentID = EntityManager.Instance.OrgId;

            System.Collections.Hashtable userProps = new System.Collections.Hashtable();
            if (e.WebTest.Context.ContainsKey("UserRole"))
            {
                userProps.Add("role", e.WebTest.Context["UserRole"]);
                er.Props = userProps;
            }
            
            System.Collections.Hashtable Entities = EntityManager.Instance.GetEntities(er);

            user = (CRMEntity)Entities[EntityNames.Users];

            crmServer = user["CrmServer"];
            tokenKey = EntityManager.Instance.ReadTokenKey(user["organizationid"]);

            orgId = new Guid(user["organizationid"]);

            e.WebTest.UserName = user["domainName"];
            e.WebTest.Password = user["userpassword"];            
        }

        public void CreateNewCompetitor_PostWebTest(object sender, PostWebTestEventArgs e)
        {
            try
            {
                if (newCompetitorId != null)
                {
//                    Guid g = EntityManager.Instance.GetOwnerGuid(new Guid(user[EntityIDNames.User]), new Guid(user["OrganizationId"]));
//                    EntityManager.Instance.AddEntity(EntityNames.Accounts, g, new string[] { "OwningUser", "AccountID", "name", "EntityManagerOwningUser" }, new string[] { user["systemuserid"], newAcctId, name, g.ToString() });
                }
            }
            finally
            {
                EntityManager.Instance.FreeEntity(user);
            }
        }

        private void NewCompetitor_ValidateResponse(object sender, ValidationEventArgs e)
        {
            string ID = null;

            int idIdx = e.Response.BodyString.IndexOf(newIdMarker);
            ID = e.Response.BodyString.Substring(idIdx + (CreateNewCompetitor.newIdMarker.Length), 36);
            try
            {
                ID = new Guid(ID).ToString();
            }
            catch (System.FormatException fe)
            {
                System.Diagnostics.Trace.WriteLine("Format exception: " + fe.ToString());
                e.IsValid = false;
                return;
            }
            e.IsValid = true;
        }

        public CreateNewCompetitor()
        {
            WebRequest.RegisterPrefix("crm", new crmRequestFactory());
            GetContextHtml_Helper.PrimaryContact(out ctxt, out ctxt_formXml, out ctxt_formSubmitId);

            gridXml = GridXmlHelper.CompetitorPageViewRefresh(-1, myCompetitorView, null);

            this.Proxy = null;
            PreWebTest += new EventHandler<PreWebTestEventArgs>(CreateNewCompetitor_PreWebTest);
            PostWebTest += new EventHandler<PostWebTestEventArgs>(CreateNewCompetitor_PostWebTest);
        }

        public override IEnumerator<WebTestRequest> GetRequestEnumerator()
        {
            this.BeginTransaction("NavCompetitorHomepage");

            _root_homepage_aspx hp = new _root_homepage_aspx(user);
            hp.etc = 123;
            yield return (hp);

            this.EndTransaction("NavCompetitorHomepage");

            this.BeginTransaction("CreateCompetitor");

            sfa_comps_edit_aspx dp = new sfa_comps_edit_aspx(user);
            yield return (dp);

            referer = dp.lastResponse.ResponseUri.AbsoluteUri;

            _forms_FormScript_js_aspx formScript = new _forms_FormScript_js_aspx(user);
            formScript.etc = 123;
            formScript.FormType = "main";
            formScript.FormName = "crmForm";
            headerItem = new WebTestRequestHeader("referer", referer);
            formScript.Headers.Add(headerItem);
            yield return (formScript);


            dp = new sfa_comps_edit_aspx(user);
            name = Utils.GetRandomString(5, 30);

            dp.crmFormSubmitXml = EntityXmlHelper.GetCreateCompetitorXml(name);
            dp.crmFormSubmitMode = 1;
            dp.CrmFormUserModified = true;
            dp.crmFormSubmitObjectType = 123;
            dp.crmFormSubmitSecurity = 65591;
            dp.crmFormSubmitOnline = 1;
            rpcInfo = Utils.GenerateWRPCToken(sfa_comps_edit_aspx.url, user, tokenKey);
            dp.CRMWRPCToken = rpcInfo.token;
            dp.CRMWRPCTokenTimeStamp = rpcInfo.timeStamp;
            dp.ValidateResponse += this.NewCompetitor_ValidateResponse;
            yield return (dp);

            //get the newly created account id out of the post reply
            int idIdx = dp.lastResponse.BodyString.IndexOf(newIdMarker);
            string tempNewCompetitorId = dp.lastResponse.BodyString.Substring(idIdx + (CreateNewCompetitor.newIdMarker.Length), 36);
            newCompetitorId = new Guid(tempNewCompetitorId).ToString();

            AppGridWebService.AppGridWebService agws = new AppGridWebService.AppGridWebService();
            WebTestRequest wtrRefresh = null;
            try { agws.Refresh(gridXml); }
            catch (crmException x)
            {
                wtrRefresh = x.wtr;
                wtrRefresh.Url = Utils.ReplaceServerName(wtrRefresh.Url, user);

                string urlPath = wtrRefresh.Url.Remove(0, crmServer.Length);
                urlPath = urlPath.Remove(0, user["organizationName"].Length + 1);

                rpcInfo = Utils.GenerateWRPCToken(urlPath, user, tokenKey);

                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctokentimestamp";
                headerItem.Value = rpcInfo.timeStamp.ToString();
                wtrRefresh.Headers.Add(headerItem);
                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctoken";
                headerItem.Value = rpcInfo.token;
                wtrRefresh.Headers.Add(headerItem);
                wtrRefresh.Method = "Post";
            }
            yield return (wtrRefresh);

            this.EndTransaction("CreateCompetitor");
        }

        private static RelatedInformation.Context ctxt;
        private static string ctxt_formXml;
        private static string ctxt_formSubmitId;
        private const string newIdMarker = @"separator + ""id=";
        private CRMEntity user;
        private string newCompetitorId;        
        private string gridXml;
        private string crmServer;
        private string tokenKey;
        private static string myCompetitorView = "00000000-0000-0000-00AA-000010001110";

        private Guid orgId;
        private string name;
        private string referer;
        private WRPCInfo rpcInfo;
        private WebTestRequestHeader headerItem;
    }
}
